package com.module.my;

import com.module.retrofit.bean.ResponseBean;
import com.module.retrofit.utils.RxSchedulers;
import com.module.retrofit.exception.ExceptionConvert;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.trello.rxlifecycle2.components.support.RxFragment;

import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import io.reactivex.Observable;

/**
 * Author: deng
 * Date: 2020/9/23
 * Description:
 */
public class NetFragment<T> extends RxFragment {

    private static String TAG = "AliFragment";

    public static NetFragment newInstance(FragmentActivity activity) {
        FragmentManager fragmentManager = activity.getSupportFragmentManager();
        NetFragment fragment = (NetFragment) fragmentManager.findFragmentByTag(TAG);
        boolean isNewInstance = fragment == null;
        if (isNewInstance) {
            fragment = new NetFragment();
            fragmentManager
                    .beginTransaction()
                    .add(fragment, TAG)
                    .commitAllowingStateLoss();
            fragmentManager.executePendingTransactions();
        }
        return fragment;
    }

    public IRxNet createObservable() {
        return new IRxNet() {
            @Override
            public <T> Observable<ResponseBean<T>> setObservable(Observable<ResponseBean<T>> observable) {
                return observable
                        .onErrorResumeNext(new ExceptionConvert<ResponseBean<T>>())
                        .compose(RxSchedulers.<ResponseBean<T>>applySchedulers())
                        //fragment中每次onStop都在onNext()之后 故改成onPause
                        .compose(NetFragment.this.<ResponseBean<T>>bindUntilEvent(FragmentEvent.PAUSE));
            }
        };
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }


}
